package com.educatioin.manage.web.pointreward.controller;

import com.educatioin.commons.util.AjaxResult;
import com.educatioin.manage.common.beans.Response;
import com.educatioin.manage.web.pointreward.entity.PointRewardProductEntity;
import com.educatioin.manage.web.pointreward.po.PointRewardProductPo;
import com.educatioin.manage.web.pointreward.repository.PointRewardProductRepository;
import com.educatioin.manage.web.pointreward.request.QueryPointRewardProductsReq;
import com.educatioin.manage.web.pointreward.response.QueryPointRewardProductsRsp;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * Created by zhangyin on 2018/5/1.
 */
@Controller
@RequestMapping("/api/pointRewardProduct")
public class PointRewardProductController {

    @Autowired
    private PointRewardProductRepository pointRewardProductRepository;

    /**
     * 分页查询积分产品列表
     * @param queryPointRewardProductsReq
     * @return
     */
    @RequestMapping("/queryPointRewardProducts")
    @ResponseBody
    public QueryPointRewardProductsRsp queryPointRewardProducts(QueryPointRewardProductsReq queryPointRewardProductsReq) {
        QueryPointRewardProductsRsp queryPointRewardProductsRsp = new QueryPointRewardProductsRsp();
        Integer page = queryPointRewardProductsReq.getPage();
        Integer limit  = queryPointRewardProductsReq.getLimit();
        if(null == page|| page<=0 || null == limit || limit< 0){
            queryPointRewardProductsRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryPointRewardProductsRsp.setReturnMsg("分页查询错误！");
            return queryPointRewardProductsRsp;
        }

        if(page > 0) {
            page = page -1;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageRequest = new PageRequest(page, limit, sort);

        String name = queryPointRewardProductsReq.getName();
        Page<PointRewardProductPo> retPage = pointRewardProductRepository.findAll((root, query, cb) -> {
                    List<Predicate> predicates = Lists.newArrayList();
                    if(StringUtils.isNoneBlank(name)) {
                        predicates.add(cb.and(cb.like(root.get("name"), name)));
                    }
                    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);
        queryPointRewardProductsRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        if(retPage.hasContent()) {
           List<PointRewardProductEntity> pointRewardProductEntities = Lists.newArrayList();
           for(PointRewardProductPo rewardProductPo: retPage.getContent()){
               PointRewardProductEntity pointRewardProductEntity = new PointRewardProductEntity();
               pointRewardProductEntity.setId(rewardProductPo.getId());
               pointRewardProductEntity.setCode(rewardProductPo.getCode());
               pointRewardProductEntity.setName(rewardProductPo.getName());
               pointRewardProductEntity.setPrice(rewardProductPo.getPrice());
               pointRewardProductEntity.setAmount(rewardProductPo.getAmount());
               pointRewardProductEntities.add(pointRewardProductEntity);
           }
           queryPointRewardProductsRsp.setData(pointRewardProductEntities);
        }
        queryPointRewardProductsRsp.setCount((int)retPage.getTotalElements());
        return queryPointRewardProductsRsp;
    }

    /**
     * 同步积分产品（新增、编辑）
     * @return
     */
    @RequestMapping("/sync")
    @ResponseBody
    public AjaxResult<String> syncPointRewardProduct(@RequestBody PointRewardProductPo pointRewardProductPo) {
        AjaxResult<String> result = new AjaxResult<>();
        if(pointRewardProductPo.getId()!=null){
            PointRewardProductPo dbPointRewardProduct = pointRewardProductRepository.findOne(pointRewardProductPo.getId());
            dbPointRewardProduct.setName(pointRewardProductPo.getName());
            dbPointRewardProduct.setShowImage(pointRewardProductPo.getShowImage());
            dbPointRewardProduct.setCode(pointRewardProductPo.getCode());
            dbPointRewardProduct.setPrice(pointRewardProductPo.getPrice());
            dbPointRewardProduct.setDetail(pointRewardProductPo.getDetail());
            dbPointRewardProduct.setDescription(pointRewardProductPo.getDescription());
            dbPointRewardProduct.setAmount(pointRewardProductPo.getAmount());
            PointRewardProductPo resp = pointRewardProductRepository.save(dbPointRewardProduct);
            if(resp == null){
                result.setCode(AjaxResult.ERROR_CODE);
                result.setMsg("更新积分产品失败");
                return result;
            }
        } else{
            PointRewardProductPo resp = pointRewardProductRepository.save(pointRewardProductPo);
            if(resp == null) {
                result.setCode(AjaxResult.ERROR_CODE);
                result.setMsg("新增积分产品失败");
                return result;
            }
        }
        return result;
    }

    /**
     * 删除积分产品（单个）
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult<String> deletePointRewardProduct(Long id) {
        AjaxResult<String> result = new AjaxResult<>();
        PointRewardProductPo po = pointRewardProductRepository.findOne(id);
        if(null == po){
            result.setCode(AjaxResult.ERROR_CODE);
            result.setMsg("找不到删除对象！");
            return result;
        }
        pointRewardProductRepository.delete(po);
        result.setCode(AjaxResult.SUCCESS_CODE);
        result.setMsg("删除成功");
        return result;
    }

    /**
     * 获取积分产品详情
     * @param pointRewardProductId
     * @return
     */
    @RequestMapping("/detail")
    @ResponseBody
    public AjaxResult<PointRewardProductPo> findById(Long pointRewardProductId) {
        AjaxResult<PointRewardProductPo> ar = new AjaxResult<>();
        PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findOne(pointRewardProductId);

        if(null == pointRewardProductPo){
            ar.setCode(AjaxResult.ERROR_CODE);
            ar.setMsg("游学产品不存在！");
            return ar;
        }

        ar.setCode(AjaxResult.SUCCESS_CODE);
        ar.setData(pointRewardProductPo);
        return ar;
    }
}
